package com.zwh.modules.goods.controller;


import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zwh.common.idgen.IdGenerate;
import com.zwh.modules.goods.constants.SecondKillConstatns;
import com.zwh.modules.goods.entity.Goods;
import com.zwh.modules.goods.rabbitmq.MessageSender;
import com.zwh.modules.goods.rabbitmq.UserBuyGoodsMessage;
import com.zwh.modules.goods.service.GoodsService;
import com.zwh.modules.order.entity.Order;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhangwenhe
 * @since 2020-10-27
 */
@Controller
@RequestMapping("/goods")
public class GoodsController { // implements InitializingBean {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private MessageSender messageSender;

    /**
     * 系统初始化
     */
//    @Override
//    public void afterPropertiesSet() {
//        QueryWrapper<Goods> queryWrapper = new QueryWrapper<Goods>();
//        queryWrapper.gt("stock_sum", 0);
//        List<Goods> goodsList = goodsService.list(queryWrapper);
//        if (goodsList == null) {
//            return;
//        }
//        for (Goods goods : goodsList) {
//            redisTemplate.opsForHash().putIfAbsent(SecondKillConstatns.second_kill_goods_stock, goods.getId(), goods.getStockSum());
//        }
//    }

    @RequestMapping(value = "/secondKillList", method = RequestMethod.POST)
    @ResponseBody
    public Object secondKillList(@RequestParam("goodsId") String goodsId) {
//        redisTemplate.opsForValue().setIfAbsent("lock", "1");
        //获取秒杀商品列表
        List seckillGoodsList = redisTemplate.boundHashOps(SecondKillConstatns.second_kill_goods_list).values();
        if (seckillGoodsList == null || seckillGoodsList.size() == 0) {
            QueryWrapper<Goods> queryWrapper = new QueryWrapper<Goods>();
            queryWrapper.gt("stock_sum", 0);
            seckillGoodsList = goodsService.list(queryWrapper);
            //将商品列表装入缓存
            System.out.println("将秒杀商品列表装入缓存");
            for (Object seckillGoods : seckillGoodsList) {
                redisTemplate.boundHashOps(SecondKillConstatns.second_kill_goods_list).put(((Goods) seckillGoods).getId(), seckillGoods);
            }
        }
        return seckillGoodsList;
    }

    /**
     * 根据商品为当前用户生成动态url
     *
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/path", method = RequestMethod.GET)
    @ResponseBody
    public Object getSecondKillPath(@RequestParam("userId") String userId, @RequestParam("goodsId") String goodsId, @RequestParam("verifyCode") String verifyCode) {
        // 获取登陆用户对象

        // 先进行验证码判断
        boolean check = goodsService.checkVerifyCode(userId, goodsId, verifyCode);
        if (!check) {
            // 验证失败返回错误
            return "验证失败返回错误";
        }
        String path = goodsService.createPath(userId, goodsId);

        return path;
    }

    @RequestMapping(value = "/{path}/doSecondKill", method = RequestMethod.POST)
    @ResponseBody
    public Object doSecondKill(@RequestParam("userId") String userId,
                               @RequestParam("goodsId") String goodsId,
                               @PathVariable("path") String path) {
        // 验证动态path是否和redis中一致
        boolean check = goodsService.checkPath(userId, goodsId, path);
        if (!check) {
            //path 校验错误
            return "校验错误";
        }
        // 是否已经下单
        Order order = goodsService.getByUserIdWithGoodsId(userId, goodsId);
        if (order != null) {
            //已经下单情况的处理
            return "已经下单,请前往订单进行处理";
        }
        //预减库存
        long stock = redisTemplate.opsForHash().increment(SecondKillConstatns.second_kill_goods_stock, goodsId, -1);
        if (stock < 0) {
            return "没有货了";
        }
        // 发送MQ消息队列
        UserBuyGoodsMessage message = new UserBuyGoodsMessage();
        message.setMessageKey(IdGenerate.nextId());
        message.setUserId(userId);
        message.setGoodsId(goodsId);
        messageSender.sendSecondKillMessage(message);
        return "排队中"; //排队中
    }

    /**
     * 获取秒杀结果
     * orderId：成功
     * -1：秒杀失败
     * 0： 排队中
     */
    @RequestMapping(value = "/result", method = RequestMethod.GET)
    @ResponseBody
    public Object miaoshaResult(@RequestParam("userId") String userId,
                                @RequestParam("goodsId") String goodsId) {
        String result = goodsService.getSecondKillResult(userId, goodsId);
        return result;
    }


    @RequestMapping(value = "/test", method = RequestMethod.GET)
    @ResponseBody
    public Object test(@RequestParam("goodsId") String goodsId) {
        long count = redisTemplate.opsForHash().increment("goodsStock", goodsId, -1);
        return count;
    }
}
